<template>
  <div class="child-list-container">
    <!-- 固定搜索栏 -->
    <div class="fixed-header">
      <div class="page-header">
        <h3>子女管理</h3>
        <div class="search-group">
          <el-input
              v-model="searchParams.childName"
              placeholder="请输入姓名"
              clearable
              style="width: 200px"
          />
          <el-input
              v-model="searchParams.phone"
              placeholder="请输入电话"
              clearable
              style="width: 200px"
          />
          <el-select
              v-model="searchParams.communityId"
              placeholder="选择社区"
              filterable
              remote
              :remote-method="filterCommunity"
              :loading="communityLoading"
              clearable
              style="width: 200px"
          >
            <el-option
                v-for="item in filteredCommunityList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
            />
          </el-select>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </div>
        <el-button type="primary" :icon="Plus" @click="handleAdd">添加子女</el-button>
      </div>
    </div>

    <el-table
        :data="childList"
        style="width: 100%"
        v-loading="loading"
        border
        stripe
        row-class-name="table-row"
    >
      <el-table-column prop="avatar" label="头像" align="center" width="100">
        <template #default="{ row }">
          <el-avatar :size="40" :src="row.avatar">
            <img src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png" alt=""/>
          </el-avatar>
        </template>
      </el-table-column>
      <el-table-column prop="childName" label="姓名" align="center" min-width="120"/>
      <el-table-column prop="phone" label="手机号" align="center" min-width="150"/>
      <el-table-column prop="communityName" label="所属社区" align="center" min-width="150"/>
      <el-table-column label="操作" align="center" width="320" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" :icon="Edit" @click="handleEdit(row)">编辑</el-button>
          <el-button type="success" :icon="View" @click="handleViewElder(row)">绑定老人</el-button>
          <el-button type="danger" :icon="Delete" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 子女表单对话框 -->
    <child-form
        ref="childFormRef"
        :is-edit="isEdit"
        :child="currentChild"
        :community-list="communityList"
        @success="handleSuccess"
    />

    <!-- 查看关联老人对话框 -->
    <el-dialog
        v-model="elderDialogVisible"
        title="关联老人"
        width="800px"
        :close-on-click-modal="false"
    >
      <div class="elder-dialog-header">
        <el-alert
            v-if="currentChildElders.length >= 2"
            title="每位子女最多只能绑定两位老人"
            type="warning"
            :closable="false"
            style="margin-right: 16px"
        />
        <el-button
            type="primary"
            @click="openBindElderDialog"
            :disabled="currentChildElders.length >= 2"
        >添加绑定
        </el-button>
      </div>
      <el-table :data="currentChildElders" style="width: 100%" border stripe
                row-class-name="table-row">
        <el-table-column prop="avatar" label="头像" width="100">
          <template #default="{ row }">
            <el-avatar :size="40" :src="row.avatar"/>
          </template>
        </el-table-column>
        <el-table-column prop="elderName" label="姓名"/>
        <el-table-column prop="phone" label="联系电话"/>
        <el-table-column label="操作" width="120">
          <template #default="{ row }">
            <el-button type="danger" @click="handleUnbindElder(row)">解除绑定</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- 绑定老人对话框 -->
    <el-dialog
        v-model="bindElderDialogVisible"
        title="添加绑定"
        width="800px"
        :close-on-click-modal="false"
    >
      <el-alert
          title="每位子女最多只能绑定两位老人"
          type="warning"
          :closable="false"
          style="margin-bottom: 16px"
      />
      <div class="bind-search-group">
        <el-input
            v-model="bindSearchParams.elderName"
            placeholder="请输入姓名"
            clearable
            style="width: 200px"
        />
        <el-input
            v-model="bindSearchParams.phone"
            placeholder="请输入电话"
            clearable
            style="width: 200px"
        />
        <el-button type="primary" @click="bindHandleSearch">搜索</el-button>
        <el-button @click="resetBindSearch">重置</el-button>
      </div>
      <el-table :data="availableElders" style="width: 100%" v-loading="loading" border stripe
                row-class-name="table-row">
        <el-table-column prop="avatar" label="头像" width="100">
          <template #default="{ row }">
            <el-avatar :size="40" :src="row.avatar"/>
          </template>
        </el-table-column>
        <el-table-column prop="elderName" label="姓名"/>
        <el-table-column prop="phone" label="联系电话"/>
        <el-table-column label="操作" width="120">
          <template #default="{ row }">
            <el-button type="primary" @click="handleBindElder(row)">绑定</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {nextTick, onActivated, onMounted, ref} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import {Delete, Edit, Plus, View} from '@element-plus/icons-vue'
import type {Child} from '@/types/child'
import type {Community} from '@/types/community'
import type {Elder} from '@/types/elder'
import {bindChildAndElder, delChild, findAllChild, getChildAndElder, unbindChildAndElder} from '@/api/child'
import {getAllCommunities} from '@/api/community'
import {getAllElders} from '@/api/elder'
import ChildForm from './ChildForm.vue'

const loading = ref(false)
const childList = ref<Child[]>([])
const communityList = ref<Community[]>([])
const childFormRef = ref()
const isEdit = ref(false)
const currentChild = ref<Child>()
const elderDialogVisible = ref(false)
const currentChildElders = ref<Elder[]>([])
const currentChildId = ref<number>()
const bindElderDialogVisible = ref(false)
const availableElders = ref<Elder[]>([])
// 其他变量不变
const communityLoading = ref(false)
const filteredCommunityList = ref<Community[]>([])

const searchParams = ref({
  childName: '',
  phone: '',
  communityId: null
})

const bindSearchParams = ref({
  elderName: '',
  phone: ''
})

// 社区过滤方法
const filterCommunity = (query: string) => {
  if (query) {
    communityLoading.value = true
    setTimeout(() => {
      filteredCommunityList.value = communityList.value.filter(item => {
        return item.name.includes(query)
      })
      communityLoading.value = false
    }, 200)
  } else {
    filteredCommunityList.value = communityList.value
  }
}

// 修改 fetchCommunityList 方法
const fetchCommunityList = async () => {
  try {
    communityList.value = await getAllCommunities()
    filteredCommunityList.value = communityList.value
  } catch (error) {
    console.error('获取社区列表失败:', error)
  }
}

const fetchChildList = async () => {
  loading.value = true
  try {
    const data = await findAllChild({
      childName: searchParams.value.childName,
      phone: searchParams.value.phone,
      communityId: searchParams.value.communityId
    })
    childList.value = data.map((child: Child) => {
      const community = communityList.value.find(c => c.id === child.communityId)
      return {
        ...child,
        communityName: community ? community.name : '无'
      }
    })
  } catch (error: any) {
    console.error('获取子女列表失败:', error)
    ElMessage.error(error.msg || '获取数据失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  fetchChildList()
}

const bindHandleSearch = () => {
  fetchAvailableElderList()
}

const fetchAvailableElderList = async () => {
  loading.value = true
  try {
    const data = await getAllElders({
      elderName: bindSearchParams.value.elderName,
      phone: bindSearchParams.value.phone
    })
    // 去掉已绑定的老人
    availableElders.value = data.filter((elder: Elder) => {
      return !currentChildElders.value.some((childElder: Elder) => childElder.id === elder.id)
    })
  } catch (error: any) {
    console.error('获取可绑定的老人列表失败:', error)
    ElMessage.error(error.msg || '获取数据失败')
  } finally {
    loading.value = false
  }
}

const resetSearch = () => {
  searchParams.value = {
    childName: '',
    phone: '',
    communityId: null
  }
  fetchChildList()
}

const resetBindSearch = () => {
  bindSearchParams.value = {
    elderName: '',
    phone: ''
  }
  fetchAvailableElderList()
}

const handleAdd = async () => {
  try {
    isEdit.value = false
    currentChild.value = undefined
    if (communityList.value.length === 0) {
      await fetchCommunityList()
    }
    await nextTick()
    childFormRef.value?.open()
  } catch (error) {
    console.error('准备添加数据失败:', error)
    ElMessage.error('准备添加数据失败')
  }
}

const handleEdit = async (row: Child) => {
  try {
    isEdit.value = true
    currentChild.value = row
    if (communityList.value.length === 0) {
      await fetchCommunityList()
    }
    if (childList.value.length === 0) {
      await fetchChildList()
    }
    await nextTick()
    childFormRef.value?.open()
  } catch (error) {
    console.error('准备编辑数据失败:', error)
    ElMessage.error('准备编辑数据失败')
  }
}

const handleViewElder = async (row: Child) => {
  currentChild.value = row
  currentChildId.value = row.id
  elderDialogVisible.value = true
  try {
    currentChildElders.value = await getChildAndElder(row.id)
  } catch (error: any) {
    console.error('获取关联老人失败:', error)
    ElMessage.error(error.msg || '获取关联老人失败')
  }
}

const handleUnbindElder = async (elder: Elder) => {
  if (!currentChildId.value || !currentChild.value) return

  try {
    await ElMessageBox.confirm('确定要解绑该老人吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await unbindChildAndElder({
      childId: currentChildId.value,
      elderId: elder.id
    })
    ElMessage.success('解绑成功')
    const updatedElders = await getChildAndElder(currentChildId.value)
    currentChildElders.value = updatedElders
    if (bindElderDialogVisible.value) {
      try {
        const data = await getAllElders({communityId: currentChild.value?.communityId})
        //  去掉已绑定的老人
        availableElders.value = data.filter((elder: Elder) => {
          return !updatedElders.some((childElder: Elder) => childElder.id === elder.id)
        })
        if (availableElders.value.length === 0) {
          ElMessage.warning('当前社区没有可绑定的老人')
        }
      } catch (error) {
        console.error('刷新可绑定老人列表失败:', error)
      }
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('解绑老人失败:', error)
      ElMessage.error(error.msg || '解绑失败')
    }
  }
}

const handleDelete = async (row: Child) => {
  try {
    await ElMessageBox.confirm('删除后将无法恢复该子女的所有信息，包括和老人的绑定信息，是否确认删除？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      draggable: true,
      closeOnClickModal: false
    })
    await delChild(row)
    ElMessage.success('删除成功')
    await fetchChildList()
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('删除子女失败:', error)
      ElMessage.error(error.msg || '删除失败')
    } else {
      ElMessage.info('已取消删除')
    }
  }
}

const handleSuccess = () => {
  fetchChildList()
}

const openBindElderDialog = async () => {
  try {
    if (!currentChild.value) {
      ElMessage.error('子女信息不能为空')
      return
    }
    if (currentChildElders.value.length >= 2) {
      ElMessage.warning('每位子女最多只能绑定两位老人')
      return
    }
    const data = await getAllElders({communityId: currentChild.value.communityId})
    // 去掉已绑定的老人
    availableElders.value = data.filter((elder: Elder) => {
      return !currentChildElders.value.some((childElder: Elder) => childElder.id === elder.id)
    })
    if (availableElders.value.length === 0) {
      ElMessage.warning('当前社区没有可绑定的老人')
      return
    }
    bindElderDialogVisible.value = true
  } catch (error: any) {
    console.error('获取老人列表失败:', error)
    ElMessage.error(error.msg || '获取老人列表失败')
  }
}

const handleBindElder = async (elder: Elder) => {
  try {
    if (!currentChild.value?.id) {
      ElMessage.error('子女ID不能为空')
      return
    }
    if (currentChildElders.value.length >= 2) {
      ElMessage.warning('每位子女最多只能绑定两位老人')
      return
    }
    await bindChildAndElder(currentChild.value.id, elder.id)
    ElMessage.success('绑定成功')
    bindElderDialogVisible.value = false
    await handleViewElder(currentChild.value)
  } catch (error: any) {
    console.error('绑定老人失败:', error)
    ElMessage.error(error.msg || '绑定失败')
  }
}

onActivated(async () => {
  await fetchCommunityList()
  await fetchChildList()
})
</script>

<style scoped>
.child-list-container {
  display: flex;
  flex-direction: column;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  height: 95%;
}

.fixed-header {
  flex-shrink: 0;
  padding-bottom: 20px;
  background-color: #fff;
  z-index: 1;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-group {
  display: flex;
  align-items: center;
  gap: 10px;
}

/* 统一输入框和按钮的宽度和间距 */
.search-group .el-input,
.search-group .el-select,
.search-group .el-button {
  margin: 0; /* 清除默认margin */
}

.bind-search-group {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
  width: 100%;
  margin-bottom: 20px;
}

/* 统一输入框和按钮的宽度和间距 */
.bind-search-group .el-input,
.bind-search-group .el-select,
.bind-search-group .el-button {
  margin: 0; /* 清除默认margin */
}

.elder-dialog-header {
  margin-bottom: 20px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

:deep(.el-table th) {
  background-color: #f5f7fa !important;
  color: #606266;
  font-weight: 600;
}

:deep(.el-table td) {
  padding: 12px 0;
}

:deep(.el-table__row:hover) {
  background-color: #f5f7fa !important;
}

:deep(.el-table--border) {
  border: 1px solid #ebeef5;
}

:deep(.el-table--border th),
:deep(.el-table--border td) {
  border-right: 1px solid #ebeef5;
  border-bottom: 1px solid #ebeef5;
}

:deep(.el-button) {
  transition: all 0.3s;
}

:deep(.el-button:hover) {
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

:deep(.el-avatar) {
  border: 2px solid #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

:deep(.el-table .cell) {
  display: flex;
  align-items: center;
  justify-content: center;
}

:deep(.el-dialog__header) {
  margin: 0;
  padding: 20px 30px;
  border-bottom: 1px solid #ebeef5;
}

:deep(.el-dialog__body) {
  padding: 20px 30px;
  color: #606266;
  font-size: 14px;
  line-height: 1.5;
}

:deep(.el-dialog__footer) {
  padding: 20px 30px;
  border-top: 1px solid #ebeef5;
}

:deep(.el-dialog__title) {
  font-size: 18px;
  font-weight: 500;
  color: #303133;
}
</style>